import { Controller, Get, Post, Patch, Body, Param, Delete, Query, UseGuards, Req } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { Limit } from '@common/utils/constants';
import { UserCreateDto, UserListDto, UserUpdateDto } from './dto';
import { UserService } from './user.service';
import { Roles } from '@zeronejs/role-easy';
import { Role } from '../../common/role/enums';
import { SkipJwtAuth, AuthService, LocalAuthGuard, Request, encryptedUserPassword } from '@zeronejs/auth';


@ApiTags('user')
@ApiBearerAuth()
@Controller()
export class UserController {
    constructor(
        private readonly userService: UserService,
        private readonly authService: AuthService
        ) {}
    /**
     * 用户注册
     */
    @ApiOperation({ summary: '用户注册', description: 'roles随意字符串，后台默认为普通用户' })
    @SkipJwtAuth()
    @Post('/user/register')
    async create(@Body() createUserDto: UserCreateDto) {
        // 删除用户传入的角色，统一默认处理为普通用户，管理员权限再做分配
        delete createUserDto.roles
        const user = await this.userService.create({
            ...createUserDto,
            password: await encryptedUserPassword(createUserDto.password),
        });
        return this.authService.login(user);
    }
    /**
     * 用户登录
     */
    @ApiOperation({ summary: '用户登录' })
    @SkipJwtAuth()
    @UseGuards(LocalAuthGuard)
    @Post('user/login')
    async login(@Req() req: Request) {
        return this.authService.login(req.user);
    }
    /**
     * 用户表列表（query）
     */
    @ApiOperation({ summary: '用户表列表（query）' })
    @Post('/user/list')
    @Roles(Role.Admin)
    queryList(@Body() dto: UserListDto) {
        return this.userService.list(dto);
    }
    /**
     * 用户表列表
     */
    @ApiOperation({ summary: '用户表列表' })
    @Get('/user/list')
    @Roles(Role.Admin)
    list(@Query() limit: Limit) {
        return this.userService.list({ limit });
    }
    // @Get('/user')
    // findAll() {
    //     return this.userService.findAll();
    // }
    /**
     * 用户表详情
     */
    @Get('/user/details/:id')
    @ApiOperation({ summary: '某个用户表信息' })
    @ApiResponse({
        status: 200,
        // description: 'The found record',
        // type: GetUserInfoResult,
    })
    details(@Param('id') id: number) {
        return this.userService.findById(id);
    }
    /**
     * 修改用户表
     */
    @Patch('/user/update/:id')
    @ApiOperation({ summary: '修改用户表信息' })
    update(@Param('id') id: number, @Body() updateUserDto: UserUpdateDto) {
        return this.userService.update(id, updateUserDto);
    }
    /**
     * 删除用户表
     */
     @Roles(Role.Admin)
    @ApiOperation({ summary: '删除用户表' })
    @Delete('/user/remove/:id')
    remove(@Param('id') id: string) {
        return this.userService.delete(+id);
    }
}
